package com.weizhu.swufer.core.loadbalance;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.google.gson.Gson;
import com.weizhu.swufer.core.entity.InvokeParam;
import com.weizhu.swufer.core.entity.RpcBaseInfo;
import com.weizhu.swufer.core.registry.ServiceRegister;
import com.weizhu.swufer.core.rpc.RpcEngine;
import com.weizhu.swufer.core.rpc.RpcRequest;

import java.util.List;
import java.util.stream.Collectors;

public abstract class AbstractLoadBalancer implements LoadBalancer{


    @Override
    public String select(InvokeParam invokeParam) {
        if (!StrUtil.isBlank(invokeParam.getTargetAddress())){
            return invokeParam.getTargetAddress();
        }
        RpcRequest rpcRequest = invokeParam.getRpcRequest();
        List<String> remoteInfoList = RpcEngine.getInstance().getRegister()
                .discover(rpcRequest.getInterfaceName());
        Gson gson = new Gson();
        List<RpcBaseInfo> rpcList = remoteInfoList.stream()
                .map(x -> gson.fromJson(x, RpcBaseInfo.class)).collect(Collectors.toList());
        if (CollUtil.isEmpty(rpcList)){
            return null;
        }
        if (rpcList.size() == 1){
            return rpcList.get(0).getAddress();
        }
        String serviceKey = rpcRequest.getInterfaceName() + "." + rpcRequest.getMethodName();
        return doSelect(serviceKey,rpcList,remoteInfoList.hashCode());
    }

    public abstract String doSelect(String serviceKey,List<RpcBaseInfo> rpcList,long listHashCode);
}
